/**
 * Copyright 2010 VTT Finnish Technical Research Centre
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.osami.syncagent.server.tcpip;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.osami.syncagent.server.SyncAgentServer;


public class SyncAgentServerThread implements Runnable{
	private SyncAgentServerTCPIP syncServer;
	private ServerSocket listener;
	public SyncAgentServerThread(SyncAgentServer serverRef)
	{
		syncServer = (SyncAgentServerTCPIP) serverRef;
	}
	@Override
	public void run() {
		/*
		Random rand = new Random();
		int low_port = 1025;
		int serv_port = 1024;
		while (serv_port < low_port)
			serv_port = rand.nextInt(65535);
		*/
		
		int serv_port = SyncAgentServerTCPIP.SERVER_PORT;
		
		int i=0;
		try{
		      listener = new ServerSocket(serv_port);
		      Socket server;

		      while((i++ < syncServer.maxConnections) || (syncServer.maxConnections == 0)){
		        server = listener.accept(); // blocks?!
		        System.out.println("Create new server listener thread ("+i+")");
		        System.out.println("Connected socket form " + server.getInetAddress().getHostAddress());
		        if(!syncServer.checkKnownClient(server.getInetAddress()))
		        {
		        	// We need to somehow get mac address from the client
		        	;
		        }
		        SyncAgentServerListenerTCPIP conn_c = new SyncAgentServerListenerTCPIP(server, syncServer);
		        Thread t = new Thread(conn_c);
		        t.start();
		      }
		} catch (IOException ioe) {
		      System.out.println("IOException on socket listen: " + ioe);
		      ioe.printStackTrace();
		}
	}
	public void shutdown()
	{
		try {
			listener.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
